package ck.tool.stocksmart;

import java.util.ArrayList;
import java.util.Calendar;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.database.Cursor;
import android.os.Binder;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
import android.os.Process;
import android.app.Activity;




public class StockAlarmService extends Service {

  public static final String NEW_ALARM_FOUND = "New_Alarm_Found";
  String temp_stock;
  private Looper mServiceLooper;
  private ServiceHandler mServiceHandler;
  private NotificationManager mNM;
  final ArrayList<String> stocklist = new ArrayList<String>();
  final ArrayList<String> stockneedalarm = new ArrayList<String>();
  private static String trans_stock;
  private boolean start = true;
  
  //long test_time;
  //Calendar calendar;
  StockFormat tempstockformat;
  
  int t = 0;
 
  

  
  StockQuoteDBAdapter stockDBAdapter_service;
  Cursor stockListCursor;
  
  Calendar calendar = Calendar.getInstance();  	
  long test_time;
  	

  
//Handler that receives messages from the thread
  private final class ServiceHandler extends Handler {
      public ServiceHandler(Looper looper) {
          super(looper);
      }
      @Override
      public void handleMessage(Message msg) {
		// Normally we would do some work here, like download a file.
          // For our sample, we just sleep for 5 seconds.
          //long endTime = System.currentTimeMillis() + 5*1000;
    	  calendar.setTimeInMillis(System.currentTimeMillis());
		  calendar.add(Calendar.SECOND, 1);
		  test_time = calendar.getTimeInMillis();
          while (start) {
              synchronized (this) {
            	  if(System.currentTimeMillis() == test_time)
            	  {
            		  try {
            			t = stockneedalarm.size();
                	  	for(int i = 0; i < stockneedalarm.size(); i++)
                	  	{
                	  		tempstockformat = stockDBAdapter_service.getToStock(stockneedalarm.get(i));
                	  		Log.v("The tempstockformat is",String.valueOf(i));
                	  		if(tempstockformat.getCurrentPrice() == tempstockformat.getRisePrice()||
                	  		   tempstockformat.getCurrentPrice() == tempstockformat.getDropPrice())
                	  		{
                	  			setTrans_stock (stockneedalarm.get(i));
                	  			showNotification(t);                	  			
                	  			stockneedalarm.remove(i);
                	  			t--;
                	  		}
                	  	}
                  	} catch (Exception e) {
                  		stopSelf(msg.arg1);
                  	}
                 	calendar.add(Calendar.SECOND, 30);
				  	test_time = calendar.getTimeInMillis();
            	  }
              }
          }
          // Stop the service using the startId, so that we don't stop
          // the service in the middle of handling another job
      }
  }
    /**
     * Class for clients to access.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with
     * IPC.
     */
    public class LocalBinder extends Binder {
        StockAlarmService getService() {
            return StockAlarmService.this;
        }
    }
    
    @Override
    public void onCreate() {
        mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

        // Display a notification about us starting.  We put an icon in the status bar.
        //showNotification();
        
        stockDBAdapter_service = new StockQuoteDBAdapter(this);

        // Open or create the database
        stockDBAdapter_service.open();
        
        stockListCursor = stockDBAdapter_service.getAllStockFormatCursor();
        
        updatestocklist();
        
        needAlarm();
        
        Log.v("NI zhen", String.valueOf(stockneedalarm.size()));
        
        if(stockneedalarm.size()!=0)
        {
        
        	HandlerThread thread = new HandlerThread("ServiceStartArguments",
        			Process.THREAD_PRIORITY_BACKGROUND);
        	thread.start();
        	Log.v("NI zhen", "SB");
        	// Get the HandlerThread's Looper and use it for our Handler 
        	mServiceLooper = thread.getLooper();
        	mServiceHandler = new ServiceHandler(mServiceLooper);
        	Message msg = mServiceHandler.obtainMessage();
            mServiceHandler.sendMessage(msg);
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("LocalService", "Received start id " + startId + ": " + intent);
        // We want this service to continue running until it is explicitly
        // stopped, so return sticky.
        //Message msg = mServiceHandler.obtainMessage();
        //msg.arg1 = startId;
        //mServiceHandler.sendMessage(msg);
        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        // Cancel the persistent notification.
        // mNM.cancel(R.string.stock_alarm_service_started);
 
        // Tell the user we stopped.
    	start = false;
        Toast.makeText(this, R.string.stock_alarm_service_stopped, Toast.LENGTH_SHORT).show();
        stockDBAdapter_service.close();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    	//return null;
    }

    // This is the object that receives interactions from clients.  See
    // RemoteService for a more complete example.
    private final IBinder mBinder = new LocalBinder();

    /**
     * Show a notification while this service is running.
     */
    private void showNotification(int id) {
    	Intent intent=new Intent(this,StockAlarm.class);
    	intent.putExtra("extra", getTrans_stock());
    	
    	Log.v("Show is",String.valueOf(t));
        // In this sample, we'll use the same text for the ticker and the expanded notification
        CharSequence text = getText(R.string.stock_alarm_service_started);

        // Set the icon, scrolling text and timestamp
        Notification notification = new Notification(R.drawable.icon, text,
                System.currentTimeMillis());

        // The PendingIntent to launch our activity if the user selects this notification
        intent.setAction(String.valueOf(System.currentTimeMillis()));
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                intent, 0);

        // Set the info for the views that show in the notification panel.
        notification.setLatestEventInfo(this, getText(R.string.stock_alarm_service_label),
                       text, contentIntent);

        // Send the notification.
        // We use a layout id because it is a unique number.  We use it later to cancel.
        
        
        notification.flags|=Notification.FLAG_AUTO_CANCEL;
        notification.defaults |= Notification.DEFAULT_SOUND; 
        mNM.notify(id, notification);
        
    }
    //Useful Service
    private void updatestocklist() {
  	  stockListCursor.requery();
  	  //Because that every times the index_ck will be initialized first; use that to be part of 
  	  //condition there while be a cann't end circle
  	  stocklist.clear();
      if(stockListCursor.moveToFirst())
  	  do {
  		     String tmp = stockListCursor.getString(stockListCursor.getColumnIndex(StockQuoteDBAdapter.KEY_STOCK));
  		     stocklist.add(tmp);
  		     Log.v("NI zhen", tmp);
  	     }while(stockListCursor.moveToNext());
      Log.v("NI zhen", "NB");
  	  }
    private void needAlarm(){
    	stockListCursor.requery();
    	if(stockListCursor.moveToFirst())
    	  	  do {
    	  		     float tmp_floata = stockListCursor.getFloat(stockListCursor.getColumnIndex(StockQuoteDBAdapter.KEY_RISE_PRICE));
    	  		     float tmp_floatb = stockListCursor.getFloat(stockListCursor.getColumnIndex(StockQuoteDBAdapter.KEY_DROP_PRICE));
    	  		     if(tmp_floata != 0||tmp_floatb != 0)
    	  		     {
    	  		    	 String tmp_string = stockListCursor.getString(stockListCursor.getColumnIndex(StockQuoteDBAdapter.KEY_STOCK));
    	  		    	 stockneedalarm.add(tmp_string);
    	  		    	Log.v("NI shi", tmp_string);
    	  		     }
    	  	     }while(stockListCursor.moveToNext());
    	stockListCursor.close();
    }

	public static void setTrans_stock(String trans_stock) {
		StockAlarmService.trans_stock = trans_stock;
	}

	public static String getTrans_stock() {
		return trans_stock;
	}
    
    
}